/**
 * Created by gastrodia on 14-7-16.
 */

var fs = require('fs');
var path = require('path');
var AESCrypt = require('./AESCrypt');

module.exports = utils = {};

utils.mkdirSync = function(dirpath,mode){
    dirpath.split('\/').reduce(function(pre, cur) {
        var p = path.resolve(pre, cur);
        if(!fs.existsSync(p)) fs.mkdirSync(p, mode || 0755);
        return p;
    }, __dirname);
}

utils.autoCreateLogDir = function(){
    utils.mkdirSync('../../logs');
}

utils.parseJson = function(str){
    var json = null;
    var error = null;
    try{
        json = JSON.parse(str);
    }catch(e){
        //老bus在接口文档里提供了对unquoted JSON的支持，为力兼容这里需要用正则表达处理一下
        //http://www.quora.com/How-can-I-parse-unquoted-JSON-with-JavaScript
        try {
            var fixedStr = str.replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:/g, '"$2": ');
            json = JSON.parse(fixedStr);
        }catch(e){
            throw e;
        }
    }
    return json;
}

var aesKey ='1234567890123456';
utils.encJson = function(obj){
    var cryptkey   = new Buffer(aesKey,'utf-8');
    var iv         = new Buffer('00000000000000000000000000000000','hex').toString('utf-8');
    var objStr = JSON.stringify(obj);
    var encStr = AESCrypt.encrypt(cryptkey, iv, objStr);
    return encStr;
}

utils.decJson = function(str){
    var cryptkey   = new Buffer(aesKey,'utf-8');
    var iv         = new Buffer('00000000000000000000000000000000','hex').toString('utf-8');
    var decStr = AESCrypt.decrypt(cryptkey, iv, str);
    var decObj = JSON.parse(decStr);
    return decObj;
}


utils.fsCache = require('./FsCache');